package com.onesports.intelligent.k12.polarlight.util;

import com.onesports.intelligent.k12.polarlight.annotation.DistributedLock;
import com.onesports.intelligent.k12.polarlight.common.utils.DateUtils;
import com.onesports.intelligent.k12.polarlight.constant.LockConstants;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author FPH
 * @since 2022年7月9日16:39:04
 */
@Component
public class CodeUtils {

    @Resource
    @Qualifier("stringRedisTemplate")
    private StringRedisTemplate stringRedisTemplate;

    @DistributedLock(value = LockConstants.AUTO_SERIAL_NUMBER, keys = "#key")
    public String autoSerialNumberNoPrefix(String key, int size) {
        Integer serialNumber = 1;
        key = "SERIAL_NUMBER:" + key;
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            stringRedisTemplate.opsForValue().increment(key, 1);
        } else {
            //如果不存在key则直接设置value为 当前当天+000001
            stringRedisTemplate.opsForValue().set(key, String.valueOf(serialNumber));
        }
        String serialNumberStr = stringRedisTemplate.opsForValue().get(key);
        return String.format("%0" + size + "d", Integer.parseInt(serialNumberStr));
    }


    @DistributedLock(value = LockConstants.AUTO_SERIAL_NUMBER, keys = "#prefix")
    public String autoSerialNumber(String prefix, int size) {
        if (null == prefix) {
            prefix = "";
        }
        if (size <= 0) {
            size = 1;
        }
        String currentDay = DateUtils.dateTimeNow(DateUtils.YYYYMMDD);
        //redis的key
        String key = "SERIAL_NUMBER:" + prefix + currentDay;
        //redis的value模板，例20220718000001
        String serialNumber = String.format(currentDay + "%0" + size + "d", 1);
        //如果存在key则在原有value序号上自增+1，如到新的一年则更新value值为 新年份+000001
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(key))) {
            stringRedisTemplate.opsForValue().increment(key, 1);
        } else {
            //如果不存在key则直接设置value为 当前当天+000001
            stringRedisTemplate.opsForValue().set(key, serialNumber);
            stringRedisTemplate.expire(key, 1, TimeUnit.DAYS);
        }
        String yearNumber = stringRedisTemplate.opsForValue().get(key);
        return prefix + yearNumber;
    }
}
